package com.example.springboot.service.impl;

import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    // 密码加密器（BCrypt算法）
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    // 登录逻辑：验证用户名和密码
    @Override
    public User login(String username, String password) {

        // 1. 根据用户名查询用户
        User user = userMapper.findByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }

        // 2. 验证密码（明文密码与加密密码比对）
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 3. 验证通过，返回用户信息（注意：实际中可脱敏，不返回密码）
        user.setPassword(null);

        return user;
    }
}
